from volcenginesdkarkruntime import Ark
import pymongo

api_key='38644548-12e0-44b6-bf40-4f5128d476f1'
Access_Key_ID='AKLTZTg4YmJiYWM2OTFjNDc3ZjliZTljMzkyYmI5YjVlNTY'
Secret_Access_Key='WkRnellqbGtaV05sWWpBNE5Ea3haRGxsT0RaalpUazVabUZtWWpobVpqVQ=='

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["doubao"]
mycol = mydb["questions"]


def get_doubao_api(api_key, Access_Key_ID, Secret_Access_Key, prompt):
    try:
        client = Ark(api_key=api_key, ak=Access_Key_ID, sk=Secret_Access_Key)
        completion = client.chat.completions.create(
            model="ep-20240819081947-6v4vl",
            messages=[
                {"role": "system", "content": "你是豆包，是由字节跳动开发的AI人工智能助手"},
                {"role": "user", "content": prompt},
            ],
        )
        return completion.choices[0].message.content
    except Exception as e:
        return e

for x in range(1,11):
# 帮助生成问答题
    prompt = '请帮我生成十个中文问答的题目，每个题目给四个选项，放到python的列表中，将各个问题的答案放入python列表中'


    result = get_doubao_api(api_key,Access_Key_ID,Secret_Access_Key,prompt)
    # print(result)
    try:
        questionStr=''
        try:
            questionStr = result.split('questions =')[1].split('```')[0].strip()
        except:
            questionStr = result.split('questions_and_answers =')[1].split('```')[0].strip()
        questions = eval(questionStr)
        try:
            questionsList = []
            for i in questions:
                queDic={}
                queDic['question']=i.get('question')
                queDic['options']=i.get('options')
                queDic['answer']=i.get('answer')
                questionsList.append(queDic)
                # print(queDic)
                # print('=================')
            x = mycol.insert_many(questionsList)
            print('插入结果：',x)
        except:
            print('')
    except IndexError:
        pass
